package me.zhengjie.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.pojo.Resp;
import me.zhengjie.pojo.sqlServer.PPStorage;
import me.zhengjie.repository.PPStorageRepository;
import me.zhengjie.service.PPStorageService;
import me.zhengjie.service.dto.PPStorageDto;
import me.zhengjie.service.dto.PPStorageQueryCriteria;
import me.zhengjie.util.EasyExcelUtil;
import me.zhengjie.utils.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "储位信息管理")
@RequestMapping("/api/ppStorage")
public class PPStorageController {

    private final PPStorageService ppStorageService;
    private final PPStorageRepository ppStorageRepository;
    private final DataSource dataSoure;
    private static final Logger ppLog = LoggerFactory.getLogger("pp");


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('ppStorage:list')")
    public void exportPPStorage(HttpServletResponse response, PPStorageQueryCriteria criteria) throws IOException {
        ppStorageService.download(ppStorageService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询储位信息")
    @ApiOperation("查询储位信息")
    @PreAuthorize("@el.check('ppStorage:list')")
    public ResponseEntity<PageResult<PPStorageDto>> queryPPStorage(PPStorageQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(ppStorageService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增储位信息")
    @ApiOperation("新增储位信息")
    @PreAuthorize("@el.check('ppStorage:add')")
    public ResponseEntity<Object> createPPStorage(@Validated @RequestBody PPStorage resources){
        ppStorageService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改储位信息")
    @ApiOperation("修改储位信息")
    @PreAuthorize("@el.check('ppStorage:edit')")
    public ResponseEntity<Object> updatePPStorage(@Validated @RequestBody PPStorage resources){
        ppStorageService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除储位信息")
    @ApiOperation("删除储位信息")
    @PreAuthorize("@el.check('ppStorage:del')")
    public ResponseEntity<Object> deletePPStorage(@RequestBody Integer[] ids) {
        ppStorageService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

//    @PostMapping("/upload")
//    @Log("上传储位信息")
//    @ApiOperation("上传储位信息")
//    public Resp uploadExcel(@RequestParam("file") MultipartFile file)  throws IOException {
//
//        List<PPStorage> fromExcel = ExcelUtil.readPPStorageFromExcel(
//                file.getInputStream(), file.getOriginalFilename());
//        Connection conn = null;
//        int updateNum = 0;
//
//        try {
//            conn = dataSoure.getConnection();
//            conn.setAutoCommit(false);
//
//            PreparedStatement insert = conn.prepareStatement("INSERT INTO PP_Storage(logicalAddressType, warehouseCode, zoneCode, storageCode, aisle, layer, `row`, `column`, locationInventoryStatus, `status`) VALUES (?,?,?,?,?,?,?,?,?,?)");
//            PreparedStatement update = conn.prepareStatement("UPDATE PPStorage set logicalAddressType=?,warehouseCode=?,palletCode=null,zoneCode=?,aisle=?,layer=?,row=?,column=?,locationInventoryStatus=?,status=? WHERE storageCode=?");
//
//            for(PPStorage ppStorage : fromExcel){
//                if (ObjectUtil.isEmpty(ppStorageRepository.findPPStorageByStorageCode(ppStorage.getStorageCode()))){
//                    insert.setInt(1,ppStorage.getLogicalAddressType());
//                    insert.setString(2,ppStorage.getWarehouseCode());
//                    insert.setString(3,ppStorage.getZoneCode());
//                    insert.setString(4,ppStorage.getStorageCode());
//                    insert.setInt(5,ppStorage.getAisle());
//                    insert.setInt(6,ppStorage.getLayer());
//                    insert.setInt(7,ppStorage.getRow());
//                    insert.setInt(8,ppStorage.getColumn());
//                    insert.setInt(9,ppStorage.getLocationInventoryStatus());
//                    insert.setInt(10,ppStorage.getStatus());
//                    int executeUpdate = insert.executeUpdate();
//                    updateNum += executeUpdate;
//                    insert.clearParameters();
//                }else {
//                    update.setInt(1,ppStorage.getLogicalAddressType());
//                    update.setString(2, ppStorage.getWarehouseCode());
//                    update.setString(3,ppStorage.getZoneCode());
//                    update.setInt(4,ppStorage.getAisle());
//                    update.setInt(5,ppStorage.getLayer());
//                    update.setInt(6,ppStorage.getRow());
//                    update.setInt(7,ppStorage.getColumn());
//                    update.setInt(8,ppStorage.getLocationInventoryStatus());
//                    update.setInt(9,ppStorage.getStatus());
//                    update.setString(10,ppStorage.getStorageCode());
//                }
//            }
//
//            conn.commit();
//
//            conn.setAutoCommit(true);
//
//            insert.close();
//            update.close();
//
//
//        } catch (Exception e) {
//            updateNum = 0;
//        } finally {
//            if (conn != null) {
//                try {
//                    conn.close();
//                } catch (SQLException e) {
//                    ppLog.error("点位插入错误", e);
//                }
//            }
//        }
//
//        return updateNum != 0 ? Resp.builder()
//                .msg("上传成功")
//                .status(200)
//                .build()
//                : Resp.builder()
//                .msg("上传失败")
//                .status(400)
//                .build();
//    }


    @PostMapping("/upload")
    @Log("上传储位信息")
    @ApiOperation("上传储位信息")
    public Resp uploadExcel(@RequestParam("file") MultipartFile file)  throws IOException {

        try {
            //使用自定义工具类读取excel
//            List<PPStorage> fromExcel = ExcelUtil.readPPStorageFromExcel(file.getInputStream(), file.getOriginalFilename());
           //使用easyexcel读取excel
            List<PPStorage> fromExcel = EasyExcelUtil.readPPStorageFromExcel(file.getInputStream(), file.getOriginalFilename());
            ppStorageService.savePPStorage(fromExcel);
            return Resp.builder().status(200).msg("上传成功").build();
        }catch (Exception e){
            return Resp.builder().status(400).msg("上传失败").build();
        }


    }



    @GetMapping("/changeStatus/{storageId}/{storageStatus}")
    @Log("更改储位状态")
    @ApiOperation("更改储位状态")
    public Resp ChangeStatus(@PathVariable("storageId")Integer storageId, @PathVariable("storageStatus") Integer storageStatus){
        int result = ppStorageRepository.updatePPStorageStatusById(storageId, storageStatus);
        if(result == 1){
            return Resp.builder()
                    .status(200)
                    .msg("储位状态更新成功")
                    .build();
        }else {
            return Resp.builder()
                    .status(200)
                    .msg("储位状态更新失败")
                    .build();
        }
    }


    @GetMapping("/findSuitableStorageCode")
    @Log("找到合适的储位")
    @ApiOperation("找到合适的储位")
    public List<String> findSuitableStorageCode(){

            List<PPStorage> ppStorageList = ppStorageService.findSuitableStorage();
            List<String> storageList = new ArrayList<>();
            for (PPStorage ppStorage : ppStorageList) {
                storageList.add(ppStorage.getStorageCode());
            }
            return storageList;

    }


}
